package com.wondertek.poms.service.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.netflix.discovery.converters.Auto;
import com.wondertek.poms.common.constant.Constants;
import com.wondertek.poms.common.exception.MessageCodes;
import com.wondertek.poms.common.log.MethodLog;
import com.wondertek.poms.common.utils.excel.ImportExcel;
import com.wondertek.poms.common.utils.validate.ValidateFilter;
import com.wondertek.poms.common.vo.PageBean;
import com.wondertek.poms.common.vo.ResultBean;
import com.wondertek.poms.core.service.IEquityNodeService;
import com.wondertek.poms.core.service.IEquityTreeService;
import com.wondertek.poms.core.service.IMamRecommendService;
import com.wondertek.poms.dao.po.*;
import com.wondertek.poms.dao.pojo.MamRecommendExcelPojo;
import com.wondertek.poms.dao.pojo.SellingPriceTagExcelPojo;
import com.wondertek.poms.service.vo.MamRecommendVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;

@RestController
@RequestMapping(value = "/mam-recommend")
public class MamRecommendController {

    @Autowired
    private IMamRecommendService mamRecommendService;
    @Autowired
    private IEquityNodeService equityNodeService;
    @Autowired
    private IEquityTreeService equityTreeService;

    @GetMapping(value = "/list")
    @ResponseBody
    public ResultBean list(MamRecommendVo mamRecommendVo,
                           @RequestParam(defaultValue = "1") int page,
                           @RequestParam(defaultValue = "20") int rows,
                           @RequestParam(defaultValue = "CREATE_TIME") String sidx,
                           @RequestParam(defaultValue = "desc") String sord){
        MamRecommend mamRecommend=new MamRecommend();
        BeanUtils.copyProperties(mamRecommendVo,mamRecommend);
        Page<MamRecommend> list=mamRecommendService.findAll(mamRecommend,page,rows,sord,sidx);
        return PageBean.ok(list.getTotalPages(),list.getTotalElements(),list.getContent());
    }

    @PostMapping(value = "/add")
    @ResponseBody
    @MethodLog(module = "权益节点与标签关联新增",insertDB=true,opterate = 1)
    public ResultBean add(@RequestBody MamRecommendVo mamRecommendVo){
        List<String> messageList = ValidateFilter.getFilterMessage(mamRecommendVo, Constants.VALIDATE_DEFAULT);
        if (!messageList.isEmpty()) {
            return ResultBean.error(messageList.toString());
        }
        String[] mamRecommendArr = mamRecommendVo.getMamRecommend().split(",|，");
        for(String temp:mamRecommendArr){
            MamRecommendVo vo=new MamRecommendVo();
            vo.setMamRecommend(temp);
            if(isRepeat(vo)){
                return ResultBean.error(MessageCodes.get(MessageCodes.M980014));
            }
            MamRecommend mamRecommend=new MamRecommend();
            mamRecommend.setMamRecommend(temp);
            mamRecommend.setEquityId(mamRecommendVo.getEquityId());
            MamRecommend.putTimeAndUser(mamRecommend);
            mamRecommendService.save(mamRecommend);
        }
        return ResultBean.ok();
    }

    @GetMapping(value = "/get-mam-recommends")
    @ResponseBody
    public ResultBean getMamRecommends(){
        return ResultBean.ok();
    }

    @GetMapping(value = "/get-enquity-nodes")
    @ResponseBody
    public ResultBean getEquityNodes(){
        return ResultBean.ok();
    }

    @DeleteMapping(value = "/delete")
    @ResponseBody
    @MethodLog(module = "权益节点与标签关联删除",insertDB=true,opterate = 3)
    public ResultBean delete(String ids){
        if (StrUtil.isBlank(ids)) {
            return ResultBean.error(MessageCodes.get(MessageCodes.M980203));
        }
        try {
            mamRecommendService.deleteMamRecommend(ids);
            return ResultBean.ok();
        }catch (Exception e){
            return ResultBean.error(e.getMessage());
        }
    }


    @PostMapping(value = "/import")
    @ResponseBody
    @MethodLog(module = "权益节点与标签关联导入",insertDB=true,opterate = 6)
    public ResultBean importMamRecommends(MultipartFile file){
        StringBuffer msg = new StringBuffer("导入数据总数->");
        StringBuffer errMessage = new StringBuffer(".错误原因是->");
        AtomicInteger errNum = new AtomicInteger();// 全局错误数
        List<MamRecommendExcelPojo> list=new ArrayList<>();
        try{
            ImportExcel ei = new ImportExcel(file, 1, 0);
            List<MamRecommendExcelPojo> dataList=ei.getDataList(MamRecommendExcelPojo.class);
            if (CollectionUtil.isNotEmpty(dataList)) {
                msg.append(dataList.size() + ".错误数据数->");
                dataList.forEach(v -> importData(errMessage, errNum, v, list));
            } else {
                return ResultBean.error(MessageCodes.get(MessageCodes.M980205));
            }

            if (CollectionUtil.isNotEmpty(list)){
                for(MamRecommendExcelPojo pojo:list){
                    MamRecommend mamRecommend=new MamRecommend();
                    mamRecommend.setMamRecommend(pojo.getMamRecommend());
                    mamRecommend.setEquityId(pojo.getEquityId());
                    MamRecommend.putTimeAndUser(mamRecommend);
                    mamRecommendService.save(mamRecommend);
                }
            }
            msg.append(errNum);
            msg.append(errMessage);
        }catch (Exception e){
            e.printStackTrace();
            return ResultBean.error(MessageCodes.get(MessageCodes.M980000));
        }
        if (errNum.get() > 0) {
            return ResultBean.error(msg.toString().replace("[", "").replace("]", "").replace("[]", "").replace("!", ""));
        }
        return ResultBean.ok();
    }


    public void importData(StringBuffer errMessage,AtomicInteger errNum,MamRecommendExcelPojo pojo,List<MamRecommendExcelPojo> list){
        if(pojo !=null){
            Boolean flag=true;
            String[] mamRecommendArr = pojo.getMamRecommend().split(",|，");
            for(String mam:mamRecommendArr){
                MamRecommendExcelPojo temp=new MamRecommendExcelPojo();
                temp.setEquityId(pojo.getEquityId());
                temp.setMamRecommend(mam);
                List<String> messageList = ValidateFilter.getFilterMessage(temp, Constants.VALIDATE_DEFAULT);
                flag = checkData(errMessage, errNum, temp, flag, messageList);
                if (flag ) {
                    list.add(pojo);
                }
            }
        }
    }

    public Boolean checkData(StringBuffer errMessage,AtomicInteger errNum,MamRecommendExcelPojo pojo,Boolean flag,List<String> messageList){
        if (flag && !messageList.isEmpty()) {
            errNum.addAndGet(1);
            flag = false;
            errMessage.append("导入出错：" + messageList.toString() + ".  ");
        }
        if(flag){
            MamRecommendVo mamRecommendVo=new MamRecommendVo();
            mamRecommendVo.setMamRecommend(pojo.getMamRecommend());
            if(isRepeat(mamRecommendVo)){
                errNum.addAndGet(1);
                flag = false;
                errMessage.append("推荐标签：" + pojo.getMamRecommend() + "导入出错：" + MessageCodes.get(MessageCodes.M980014) + ".  ");
            }
        }
        if(flag){
            List<EquityNode> list=equityNodeService.findAllByNodeName(pojo.getEquityId());
            if(list.size()==0){
                errNum.addAndGet(1);
                flag = false;
                errMessage.append("导入出错：权益节点名："+pojo.getEquityId()+"不存在.  ");
            }else {
                Boolean status=false;
                for(EquityNode node:list){
                    EquityTree tree=equityTreeService.findById(node.getTreeId());
                    if("0".equals(tree.getActiveStatus())){
                        status=true;
                        break;
                    }
                }
                if(!status){
                    errNum.addAndGet(1);
                    flag = false;
                    errMessage.append("导入出错：权益节点名："+pojo.getEquityId()+"所在的权益树未发布.  ");
                }
            }
        }

        return flag;
    }

    public Boolean isRepeat(MamRecommendVo mamRecommendVo){
        MamRecommend temp=new MamRecommend();
        temp.setMamRecommend(mamRecommendVo.getMamRecommend());
        Optional<MamRecommend> opt=mamRecommendService.findOne(Example.of(temp));
        if(opt.isPresent()){
            MamRecommend mamRecommend=opt.get();
            if(mamRecommendVo != null && mamRecommend.getId() != mamRecommendVo.getId()){
                return true;
            }
            if(mamRecommendVo.getId() ==null){
                return true;
            }
        }
        return false;
    }
}
